<template>
  <div>
    <van-nav-bar
      title="注册用户"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <div class="register-panel">
      <van-field
        v-model="username"
        label="用户名"
        placeholder="请输入用户名"
        :error-message="usernameErrorMsg"
      ></van-field>
      <van-field
        v-model="password"
        label="密码"
        placeholder="请输入用户名"
        type="password"
        :error-message="passwordErrorMsg"
      ></van-field>
    </div>
    <div class="register-button">
      <van-button
        type="primary"
        size="large"
        @click="registerAction"
        :loading="loading"
      >马上注册</van-button>
    </div>
  </div>
</template>
<script>
import url from '../../serviceApi.config'
export default {
  data() {
    return {
      username: '',
      password: '',
      loading: false,
      passwordErrorMsg: '',
      usernameErrorMsg: ''
    }
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1)
    },
    checkForm() {
      let isOk = true
      // 验证用户名
      if(this.username.length < 5) {
        this.usernameErrorMsg = '用户名不能小于5位'
        isOk = false
      } else {
        this.usernameErrorMsg = ''
      }
      // 验证密码
      if(this.password.length < 6) {
        this.passwordErrorMsg = '密码不能小于6位'
        isOk = false
      } else {
        this.passwordErrorMsg = ''
      }
      return isOk
    },
    registerAction() {
      if(this.checkForm()) {
        this.registerUser()
      }
    },
    async registerUser() {
      const {data: res} = await this.$http.post(url.registerUser, {username: this.username, password: this.password})
      if (res.code == 200) {
        this.$toast.success('注册成功')
        this.$router.push('/')
      } else {
        console.log(res.message)
         this.$toast.fail('注册失败')
         this.loading = false
      }
    }
  }
}
</script>
<style scoped>
.register-panel {
  width: 96%;
  border-radius: 5px;
  margin: 20px auto;
  padding-bottom: 50px;
}
.register-button {
  padding-top: 10px;
}
</style>